package com.tacademy.android.lbs.friend;

import java.util.Date;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.tacademy.android.lbs.PMF;
import com.tacademy.android.lbs.friend.model.UserLocation;

public class FriendDAO {
	@SuppressWarnings("unchecked")
	public List<UserLocation> selectUserList() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<UserLocation> userList, detached = null;
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(UserLocation.class.getName());
			query.append("  order by updateDate desc");
			
			userList = (List<UserLocation>)pm.newQuery(query.toString()).execute();
			detached = (List<UserLocation>) pm.detachCopyAll(userList);
		} finally {
			pm.close();
		}
		return detached;
	}
	
	@SuppressWarnings("unchecked")
	public UserLocation selectUserByUserId(String userId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		UserLocation detached = null;
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(UserLocation.class.getName());
			query.append("  where userId == ").append("'").append(userId).append("'");
			List<UserLocation> userList = (List<UserLocation>)pm.newQuery(query.toString()).execute();
			if (userList != null && userList.size() > 0) {
				detached = pm.detachCopy(userList.get(0));
			}
		} finally {
			pm.close();
		}
		return detached;
	}
	
	public void updateLocation(UserLocation user) throws UserNotFoundException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			UserLocation storedUser = pm.getObjectById(UserLocation.class, user.getUserId());
			storedUser.setLatitude(user.getLatitude());
			storedUser.setLongitude(user.getLongitude());
			storedUser.setUpdateDate(new Date());
		} catch (JDOObjectNotFoundException e) {
			throw new UserNotFoundException(e.getMessage(), e.getCause());
		} finally {
			pm.close();
		}
		
	}
	
	public void saveUser(UserLocation userLocation) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(UserLocation.class.getName());
			query.append("  where userId == '").append(userLocation.getUserId()).append("'");
			
			@SuppressWarnings("unchecked")
			List<UserLocation> userLocations = (List<UserLocation>)pm.newQuery(query.toString()).execute();
			if (userLocations.size() > 0) {
				UserLocation storedUserLocation = userLocations.get(0);
				userLocation.setKey(storedUserLocation.getKey());
			}
			userLocation.setUpdateDate(new Date());
			pm.makePersistent(userLocation);
		} finally {
			pm.close();
		}
	}
}
